package com.lagou.niancheng.rpc.server.spring;

import com.lagou.niancheng.rpc.server.SimpleRpcServerProvider;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.core.annotation.AnnotationUtils;

/**
 * serviceProvider扫描器
 * 该扫描器会将spring容器中所有标注有ServiceProvider的注解的类注册到服务注册中心中
 *
 * @author 大犬
 * @date 2020/5/1
 */
public class ServiceProviderScanner implements BeanPostProcessor {
    private SimpleRpcServerProvider simpleRpcServerProvider;

    public ServiceProviderScanner(SimpleRpcServerProvider simpleRpcServerProvider) {
        this.simpleRpcServerProvider = simpleRpcServerProvider;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        Class<?> aClass = bean.getClass();
        // 获取bean上是否有ServiceProvider注解
        ServiceProvider serviceProvider = AnnotationUtils.findAnnotation(aClass, ServiceProvider.class);
        if (serviceProvider == null) {
            return null;
        }
        // 获取接口
        Class<?>[] interfaces = aClass.getInterfaces();
        if (interfaces == null) {
            return null;
        }
        // 将服务提供者注册到simpleRpc服务注册中心
        for (Class<?> anInterface : interfaces) {
            simpleRpcServerProvider.addProvider(anInterface, bean);
        }
        return null;
    }
}
